import React, { useState, useEffect } from "react";
import { Page, Text } from "zmp-ui";
import { useNavigate } from "react-router-dom";
import { useI18n } from "../i18n";
import { orderApi } from "../api/login";
import { OrderItem, OrderStatus, OrderStatusText } from "../types/order";
import Navbar from "../components/navbar";

const Orders: React.FunctionComponent = () => {
  const { t } = useI18n();
  const navigate = useNavigate();
  const [orders, setOrders] = useState<OrderItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string>('');

  // 获取订单数据
  const fetchOrders = async () => {
    setLoading(true);
    setError('');
    
    try {
      const response = await orderApi.getOrderList(0);
      // TODO: 这个接口返回格式不同，直接使用data字段
      if (response && response.data) {
        setOrders(response.data || []);
      } else {
        setError('获取订单数据失败');
      }
    } catch (err: any) {
      console.error('获取订单数据错误:', err);
      setError(err.message || '获取订单数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchOrders();
  }, []);

  // 根据后端逻辑判断订单状态
  const getOrderStatus = (order: OrderItem): OrderStatusText => {
    if (order.using_status === 1) {
      return 'renting'; // 使用中
    } else if (order.using_status > 1 && !order.is_pay) {
      return 'pendingPayment'; // 待付款
    } else if (order.using_status > 1 && order.is_pay) {
      return 'completed'; // 已完成
    } else {
      return 'completed'; // 默认已完成
    }
  };

  const getStatusColor = (order: OrderItem): string => {
    const status = getOrderStatus(order);
    switch (status) {
      case 'renting': // 使用中
        return '#FFD700';
      case 'pendingPayment': // 待付款
        return '#FF6B6B';
      case 'completed': // 已完成
        return '#4ECDC4';
      default:
        return '#666';
    }
  };

  const getStatusDisplayText = (order: OrderItem): string => {
    const status = getOrderStatus(order);
    switch (status) {
      case 'renting':
        return t("orders.renting");
      case 'pendingPayment':
        return t("orders.pendingPayment");
      case 'completed':
        return t("orders.completed");
      default:
        return '未知状态';
    }
  };

  const handleOrderClick = (orderId: number) => {
    navigate(`/order-detail/${orderId}`);
  };

  const handlePayClick = (orderId: number) => {
    // 处理支付逻辑
    console.log("Pay for order:", orderId);
  };

  return (
    <Page className="page" style={{ backgroundColor: '#F5F5F7', padding: 0 }}>
      {/* 顶部导航栏 */}
      <div style={{ position: 'sticky', top: 0, zIndex: 100 }}>
        <Navbar title={t("orders.title")} />
      </div>

      {/* 错误提示 */}
      {error && (
        <div style={{
          margin: '12px',
          padding: '12px 16px',
          background: '#ffebee',
          borderRadius: 8,
          color: '#c62828',
          fontSize: 14,
          textAlign: 'center'
        }}>
          {error}
        </div>
      )}

      {/* 订单列表 */}
      <div style={{ padding: '12px' }}>
        {loading ? (
          /* 加载状态 */
          <div style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '60px 20px',
            color: '#666'
          }}>
            <div style={{ fontSize: '48px', marginBottom: '16px' }}>⏳</div>
            <div style={{ fontSize: '16px' }}>加载中...</div>
          </div>
        ) : orders.length > 0 ? (
          orders.map((order) => (
            <div
              key={order.id}
              style={{
                backgroundColor: '#fff',
                borderRadius: '12px',
                marginBottom: '12px',
                padding: '0',
                boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                cursor: 'pointer',
                overflow: 'hidden'
              }}
              onClick={() => handleOrderClick(order.id)}
            >
              {/* 顶部状态和金额 */}
              <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                padding: '16px 20px',
                borderBottom: '1px solid #f0f0f0'
              }}>
                <div style={{
                  fontSize: '16px',
                  fontWeight: '500',
                  color: '#333'
                }}>
                  {getStatusDisplayText(order)}
                </div>
                <div style={{
                  fontSize: '18px',
                  fontWeight: 'bold',
                  color: '#FF6B35'
                }}>
                  ₫ {order.fee.toFixed(2)}
                </div>
              </div>

              {/* 订单详情 */}
              <div style={{ padding: '16px 20px' }}>
                <div style={{ marginBottom: '12px' }}>
                  <div style={{
                    fontSize: '14px',
                    color: '#666',
                    marginBottom: '4px'
                  }}>
                    订单编号: {order.id}
                  </div>
                  <div style={{
                    fontSize: '14px',
                    color: '#666',
                    marginBottom: '4px'
                  }}>
                    柜机SN: {order.box1_device_uuid}
                  </div>
                  <div style={{
                    fontSize: '14px',
                    color: '#666',
                    marginBottom: '4px'
                  }}>
                    租借时间: {order.borrow_time}
                  </div>
                  <div style={{
                    fontSize: '14px',
                    color: '#666',
                    marginBottom: '4px'
                  }}>
                    租借地点: 未知地点
                  </div>
                  <div style={{
                    fontSize: '14px',
                    color: '#666',
                    lineHeight: '1.4'
                  }}>
                    计费规则: 前{order.rule_minute_free || 30}分钟免费, {order.rule_cycle_fee || 0.1}₫/{order.rule_minute_cycle || 60}分钟, {order.rule_day_fee || 100000}₫/24小时
                  </div>
                </div>
              </div>

              {/* 底部操作区域 */}
              {getOrderStatus(order) === 'pendingPayment' ? (
                <div style={{
                  borderTop: '1px solid #f0f0f0',
                  padding: '12px 20px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  backgroundColor: '#fff5f5'
                }}>
                  <div style={{
                    fontSize: '14px',
                    fontWeight: '500',
                    color: '#FF6B6B',
                    flex: 1
                  }}>
                    {t("orders.goToPay")}
                  </div>
                  <div style={{ fontSize: '16px', color: '#FF6B6B' }}>→</div>
                </div>
              ) : (
                <div style={{
                  borderTop: '1px solid #f0f0f0',
                  padding: '12px 20px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  backgroundColor: '#fafafa'
                }}>
                  <div style={{
                    fontSize: '14px',
                    fontWeight: '500',
                    color: '#333',
                    flex: 1
                  }}>
                    查看订单
                  </div>
                  <div style={{ fontSize: '16px', color: '#666' }}>→</div>
                </div>
              )}
            </div>
          ))
        ) : (
          /* 空状态 */
          <div style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '60px 20px',
            color: '#666'
          }}>
            <div style={{ fontSize: '48px', marginBottom: '16px' }}>📋</div>
            <div style={{ fontSize: '16px', marginBottom: '8px' }}>暂无订单</div>
            <div style={{ fontSize: '14px', color: '#999' }}>您还没有任何订单记录</div>
          </div>
        )}
      </div>
    </Page>
  );
};

export default Orders;


